<template>
	<view class="spc-xr-chart">
		<!-- 均值图 -->
		<qiun-data-charts ref="meanChart" type="line" :opts="meanChartOpts" :ontouch="true" onzoom
			:chartData="meanChartData" @getIndex="onMeanChartIndex"></qiun-data-charts>

	</view>
</template>

<script>
	export default {
		name: "SpcYBChart",
		props: {
			data: {
				type: Array,
				required: true
			},
			spec: {
				type: Object,
				default: () => ({
					usl: null,
					lsl: null,
					target: null
				})
			}
		},
		data() {
			return {
				meanChartData: {},
				meanChartOpts: {
					legend: {
						show: false
					},
					xAxis: {
						disableGrid: true
					},
					yAxis: {}, // 会在 processData 中动态生成
					extra: {
						line: {
							type: "straight",
							animation: true,
							disableLegend: false
						},
						markLine: { // 标记线配置
							data: [] // 会在 processData 中动态生成
						}
					}
				},
			};
		},
		// watch: {
		// 	data: {
		// 		handler(newVal) {
		// 			this.processData(newVal);
		// 		},
		// 		immediate: true
		// 	}
		// },
		mounted() {
			this.processData(this.data);
		},
		methods: {
			processData(data) {
				if (!data || data.length === 0) return;

				console.log(data);
				let xLabels = []; // x轴坐标数据
				let valData = []; // 数据
				data.forEach((item, index) => {
					item.samples.forEach((row, ind) => {
						xLabels.push(index + 1);
						valData.push(row)
					})
				});


				const meanYAxisOptions = this.calculateMeanYAxisOptions(valData, this.spec);
				console.log(meanYAxisOptions);

				this.meanChartData = {
					categories: xLabels,
					series: [{
						name: " ",
						data: valData,
						color: "#1890FF"
					}]
				};
				let meanMarkLines = [];

				// 如果有USL/LSL/Target，添加到标记线
				if (this.spec.usl !== null) {
					meanMarkLines.push({
						labelText: 'USL=' + this.spec.usl.toFixed(3),
						value: this.spec.usl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				if (this.spec.lsl !== null) {
					meanMarkLines.push({
						labelText: 'LSL=' + this.spec.lsl.toFixed(3),
						value: this.spec.lsl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				if (this.spec.target !== null) {
					meanMarkLines.push({
						labelText: 'Target=' + this.spec.target.toFixed(3),
						value: this.spec.target.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				// 更新均值图配置
				this.meanChartOpts = {
					enableScroll: true,
					padding: [20, 80, 0, 0],
					legend: {},
					xAxis: {
						scrollShow: true,
						itemCount: 6,
						disableGrid: true
					},
					yAxis: meanYAxisOptions,
					extra: {
						line: {
							type: "straight",
							animation: true,
							disableLegend: false
						},
						markLine: {
							type: 'dash',
							dashLength: 16,
							data: meanMarkLines
						}
					}
				};

			},


			// 计算均值图Y轴范围（严格使用USL/LSL作为边界）
			calculateMeanYAxisOptions(values, spec) {
				if (!values || values.length === 0) {
					return {
						format: val => val.toFixed(3),
						data: [{
							min: 0,
							max: 10,
							tofix: 2
						}] // 空数据默认范围
					};
				}

				// 1. 获取数据实际分布范围
				const dataMin = Math.min(...values);
				const dataMax = Math.max(...values);
				const dataRange = dataMax - dataMin;

				// 2. 基础边界计算（结合规格线和实际数据）
				let yMin = spec.lsl !== null ? Math.min(spec.lsl, dataMin) : dataMin;
				let yMax = spec.usl !== null ? Math.max(spec.usl, dataMax) : dataMax;

				// 3. 增加安全边距（避免数据紧贴边界，占总范围的5%）
				const padding = dataRange > 0 ? dataRange * 0.05 : 0.1; // 无波动时默认边距
				yMin -= padding;
				yMax += padding;

				// 4. 处理特殊情况：所有数据相同或范围极小
				if (yMax - yMin < 0.001) {
					const mid = (yMin + yMax) / 2;
					yMin = mid - 0.5;
					yMax = mid + 0.5;
				}

				// 5. 确保Y轴起点合理性（非负数据不显示负轴）
				if (dataMin >= 0 && yMin < 0) {
					yMin = 0;
				}

				// 6. 精确格式化（保留更多小数位计算，避免四舍五入导致范围缩小）
				const precision = 3;
				const factor = Math.pow(10, precision);
				yMin = Math.floor(yMin * factor) / factor;
				yMax = Math.ceil(yMax * factor) / factor;

				return {
					format: val => val.toFixed(precision),
					data: [{
						min: yMin,
						max: yMax,
						tofix: precision
					}]
				};
			},

			// 优化后的极差图Y轴范围计算
			calculateRangeYAxisOptions(values) {
				if (!values || values.length === 0) {
					return {
						format: val => val.toFixed(3),
						data: [{
							min: 0,
							max: 10,
							tofix: 2
						}]
					};
				}

				const dataMax = Math.max(...values);
				const dataMin = Math.min(...values);
				const dataRange = dataMax - dataMin;

				// 极差图从0开始，上限取数据最大值加边距
				let yMax = dataMax;

				// 增加边距（10%）
				const padding = dataRange > 0 ? dataRange * 0.1 : 0.1;
				yMax += padding;

				// 处理数据全为0的特殊情况
				if (yMax <= 0) {
					yMax = 1;
				}

				// 确保范围不会过小
				if (yMax < 0.5) {
					yMax = 0.5;
				}

				// 精确格式化
				const precision = 3;
				yMax = Math.ceil(yMax * Math.pow(10, precision)) / Math.pow(10, precision);

				return {
					format: val => val.toFixed(precision),
					data: [{
						min: 0,
						max: yMax,
						tofix: precision
					}]
				};
			},

		

			onMeanChartIndex(e) {
				const index = e.currentIndex.index;
				// if (typeof index === "number") {
				//     this.$refs.rangeChart.showToolTip(index);
				// }
			},
			onRangeChartIndex(e) {
				const index = e.currentIndex.index;
				// if (typeof index === "number") {
				//     this.$refs.meanChart.showToolTip(index);
				// }
			}
		}
	};
</script>

<style scoped>
	.spc-xr-chart {
		display: flex;
		flex-direction: column;
		padding: 20rpx;
	}

	qiun-data-charts {

		width: 100%;
		height: 300px;
		margin-bottom: 40rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
	}
</style>